<template>
  <div class="floor">
    <div
      class="recommend"
      v-if="recommendFlag"
      :style="{ marginTop: i + 'px' }"
    ></div>
    <h4>目录</h4>
    <div style="max-height: 80vh">
      <ul class="floorul">
        <li
          :class="index === 0 ? 'active' : ''"
          style="height: 32px"
          v-for="(item, index) in list"
          :key="index"
        >
          <span
            style="
              padding-left: 12px;
              cursor: pointer;
              --dot-left: 0px;
              --dot-width: 6px;
            "
            >{{ item.innerHTML }}</span
          >
        </li>
        <div class="_1Q_nOs9KoJ4s9_MZ1Ojq-A" style="top: 0px"></div>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: [],
      recommendFlag: false,
      i: 0,
    };
  },
  props: ["label"],
  mounted() {
    this.$nextTick(() => {
      let labelh1 = [...document.querySelectorAll(".markdown h1")];
      let labelh2 = [...document.querySelectorAll(".markdown h2")];
      let labelh3 = [...document.querySelectorAll(".markdown h3")];
      this.list = [labelh1, labelh2, labelh3].flat();
      // 滚动事件
      window.addEventListener("scroll", this.headleScroll, true);
    });
  },
  methods: {
    headleScroll() {
      console.log(1, "56");
      let scroll =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      if (scroll > this.i || scroll === 0) {
        this.i = scroll;
        this.recommendFlag = false;
      } else {
        this.i = scroll;
        this.recommendFlag = true;
      }
    },
  },
  updated() {
    let floors = this.list;
    //获取楼层导航
    let floorNavs = document.querySelectorAll(".floorul>li");
    //滚动监听
    floorNavs.forEach((item, index) => {
      item.onclick = () => {
        window.scrollTo(0, this.list[index].offsetTop);
      };
    });
    window.onscroll = function () {
      //获取滚动条高度，兼容ie
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      //符合点亮条件的楼层索引
      let activeIndex;
      //楼层导航图标点亮控制
      floors.forEach((floor, index) => {
        //检查各楼层顶端距离视窗顶端距离，如果满足条件则修改楼层图标
        floor.offsetTop - 100 <= scrollTop ? (activeIndex = index) : null;
      });
      //根据索引数设置楼层样式
      floorNavs.forEach((nav, index) => {
        index === activeIndex
          ? nav.classList.add("active")
          : nav.classList.remove("active");
      });
    };
  },
};
</script>

<style scoped>
.floor {
  width: 260px;
  position: sticky;
  top: 20px;
  right: 30px;
}
li {
  line-height: 32px;
}
ul li:hover {
  color: #ff0064;
}
.active {
  background: #f0f0f0;
  color: var(--primary-color);
}
</style>